<?php

namespace app\api\controller\group;

use app\api\controller\AuthController;
use app\api\service\GroupOrderService;
use app\api\service\PaymentService;
use think\exception\ValidateException;
use think\facade\Db;
use WeChat\Pay;

class OrderController extends AuthController
{
    /**
     *
     * 获取订单列表
     * */
    public function index()
    {
        $activity_status = $this->request->param('activity_status');

        $user_id = $this->request->user['user_id'];

        $orders = GroupOrderService::getGroupActivityList($user_id,$activity_status);


        return json(['code' => 1, 'data' => $orders, 'msg' => '请求成功!']);
    }

    /**
     *
     * 获取订单详情
     * */
    public function read()
    {
        $group_order_id = $this->request->param('group_order_id/d');

        if (empty($group_order_id)){
            return json(['code' =>0, 'msg' => '缺少参数!']);
        }

        $order = GroupOrderService::findOrder($group_order_id);

        return json(['code' => 1, 'data' => $order, 'msg' => '请求成功!']);
    }

    /**
     * 生成订单
     * */
    public function save()
    {
        $param = $this->request->param();

        try{
            validate('GroupOrderValidate')->check($param);
        }catch (ValidateException $e){
            return json(['code' => 0,'msg' => $e->getError()]);
        }
        $logistics_mode = empty($param['logistics_mode']) ? 1 : 2;//1、快递 2、自提
        $param['logistics_mode'] = $logistics_mode;
        $user_id = $this->request->user['user_id'];

     /*   $record_id = GroupOrderService::findUserGroupActivityRecord($user_id,$param['group_activity_id']);

        if (!empty($record_id)){
            return json(['code' => 0,'msg' => '同一活动只能参加一次']);
        }*/

        if ($param['logistics_mode'] != 1) {
            if (empty($param['pick_point_id'])) {
                return json(['code' => 0, '请选择自提点']);
            }
            $is_pick_point = Db::name('pick_point')->where(['store_id' => $param['store_id'], 'status' => 1, 'id' => $param['pick_point_id'], 'delete_time' => 0])->find();
            if (empty($is_pick_point)) {
                return json(['code' => 0, '自提点不存在']);
            }
        }

        if (!empty($param['group_goods_id']) && empty($param['sku_id'])){
            $goods = GroupOrderService::findSingleActivityGroupGoods($param['group_goods_id'],$param['group_activity_id']);
            if ($goods['spec_type']==2){
                return json(['code' => 0,'msg' => '非法请求group_goods_id!']);
            }
        }

        if (!empty($param['group_goods_id']) && !empty($param['sku_id'])){
            $goods =  GroupOrderService::findManyActivityGroupGoods($param['sku_id'],$param['group_activity_id']);
        }
       
        if (empty($goods)){
            return json(['code' => 0,'msg' => '商品已下架']);
        }

        if ($goods['end_time']<= time()){
            return json(['code' => 0,'msg' => '活动已结束']);
        }

        $param['buy_num'] = isset($data['buy_num']) ? $data['buy_num'] : 1;

        if ($goods['stock']< $param['buy_num']){
            return json(['code' => 0,'msg' => '库存不足']);
        }


      /*  if ($goods['group_num'] !=-1){
            $count = GroupOrderService::checkGroupNum($goods['group_activity_id']);
            if ($count == $goods['group_num']){
                return json(['code' => 0,'msg' => '活动已结束']);
            }

        }*/

        $user = GroupOrderService::getUserInfo($user_id);


        if ($goods['spec_type'] ==1){
            $goods['image'] = $goods['main_image'];
        }

        if ($goods['spec_type'] ==2){
            $goods['image'] = !empty($goods['image']) ? $goods['image'] : $goods['main_image'];
        }



        // $real_amount = number_format((float)$goods['group_price']*$param['buy_num'],2);
        $real_amount = bcmul($goods['group_price'], $param['buy_num'], 2);
        // var_dump($real_amount);exit;
        $order_no = PaymentService::generateOrderNum();

        $out_trade_no = PaymentService::generateOrderNum(10);

        $data = array_merge($user,$param,$goods,[
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
            'real_amount' => $real_amount
        ]);

        /**
         * 保存订单信息
         * */

        $group_order_id = GroupOrderService::saveOrder($data);

        if (empty($group_order_id)){
            return  json(['code' =>0, 'msg' => '下单失败!']);
        }


        $config = PaymentService::findPaymentConfig($param['store_id'],$param['payment_type']);

        if (empty($config)){
            return  json(['code' =>0, 'msg' =>'支付异常!']);
        }

        if ($goods['prepayment_amount']>0){
            $real_amount = (float)$goods['prepayment_amount'];
        }
        
        $payment_data = [
            'config' => $config,
            'trade_method' => $data['payment_type'],
            'out_trade_no' => $out_trade_no,
            'real_amount' => $real_amount,
        ];

        
        if ($data['payment_type'] == 1){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/group/order/trade/wx/notify';
        }

        if ($data['payment_type'] == 2){
            $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/group/order/trade/ali/notify';
        }


        $prepay_info = PaymentService::createOrder($payment_data);
      
        if (!empty($prepay_info)){
            return json([
                'code' =>1,
                'data' => [
                    'out_trade_no' => $out_trade_no,
                    'prepay_info' => $prepay_info
                ],
                'msg' => '下单成功!'
            ]);
        }

        return  json(['code' =>0, 'msg' => '下单失败!']);
    }

}